package com.xyq.fs.index;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;

import org.apache.lucene.document.TextField;

import com.xyq.fs.base.MyDirectoryS;
import com.xyq.fs.constants.FieldConstant;

import com.xyq.fs.util.FileCodingUtil2;

/**
 * 索引txt文本
 * 
 * @author xyqq
 *
 */
public class IndexTxtFiles implements IndexFileInf {

	@Override
	public void indexFile(File file, String upFileName, String suffix) {

		Document doc = getSimDoc(file, upFileName, suffix);

		if (file.length() > 0) {
			try {
				suffix = FileCodingUtil2.getCharsetName(file, 100);
				try (FileInputStream fis = new FileInputStream(file);
						Reader reader = new InputStreamReader(fis, suffix);) {
					TextField tx = new TextField(FieldConstant.FILE_CONTENT, reader);
					doc.add(tx);
					MyDirectoryS.addDocument(doc);
					tx = null;
				}
			} catch (IOException e) {
				System.out.println(file + "拒绝访问");
			} finally {
				suffix = null;
				file = null;
				upFileName = null;
				doc = null;
			}
		}
	}

	StringBuilder sb = new StringBuilder();

	public String getContent(File file, String upFileName) {

		sb.setLength(0);
		String str;
		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(new FileInputStream(file), FileCodingUtil2.getCharsetName(file, 1024)));) {
			int num = 0;
			while ((str = reader.readLine()) != null) {
				if (str.trim().length() > 0) {
					sb.append(str).append("<br/>");
					num++;
				}
				if (num > 300)
					break;
			}
			str = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		file = null;
		upFileName = null;
		return sb.toString();
	}

	public static void main(String[] args) throws IOException {

		Path p = Paths.get("F:\\updatedate.txt");
		String str = FileCodingUtil2.getCharsetName(p.toFile(), 1024);
		System.out.println(str);
		Files.readAllLines(p, Charset.forName("Unicode")).forEach(s -> {
			System.out.println(s);
		});
	}
}
